---
import type { __experimental_SubscriptionDetailsButtonProps } from '@clerk/shared/types';

import type { HTMLTag, Polymorphic } from 'astro/types';
import type { ButtonProps } from '../../types';
import { addUnstyledAttributeToFirstTag, logAsPropUsageDeprecation } from './utils';

type Props<Tag extends HTMLTag = 'button'> = Polymorphic<ButtonProps<Tag>> &
  Omit<__experimental_SubscriptionDetailsButtonProps, 'onSubscriptionCancel'> & { clickIdentifier?: string };

import { generateSafeId } from '@clerk/astro/internal';

const safeId = generateSafeId();

if ('as' in Astro.props) {
  logAsPropUsageDeprecation();
}

const { as: Tag = 'button', asChild, for: _for, clickIdentifier, subscriptionDetailsProps, ...props } = Astro.props;

const subscriptionDetailsOptions = {
  for: _for,
  clickIdentifier,
  ...subscriptionDetailsProps,
};

let htmlElement = '';

if (asChild) {
  htmlElement = await Astro.slots.render('default');
  htmlElement = addUnstyledAttributeToFirstTag(htmlElement, safeId);
}
---

{
  asChild ? (
    <Fragment set:html={htmlElement} />
  ) : (
    <Tag
      {...props}
      data-clerk-unstyled-id={safeId}
    >
      <slot>Subscription details</slot>
    </Tag>
  )
}

<script is:inline define:vars={{ props, subscriptionDetailsOptions, safeId }}>
  const btn = document.querySelector(`[data-clerk-unstyled-id="${safeId}"]`);

  btn.addEventListener('click', () => {
    const clerk = window.Clerk;

    // Authentication checks
    if (!clerk.user) {
      throw new Error('Ensure that `<SubscriptionDetailsButton />` is rendered inside a `<SignedIn />` component.');
    }

    if (!clerk.organization && subscriptionDetailsOptions.for === 'organization') {
      throw new Error(
        'Wrap `<SubscriptionDetailsButton for="organization" />` with a check for an active organization.',
      );
    }
    if (subscriptionDetailsOptions.clickIdentifier) {
      const clickEvent = new CustomEvent('clerk:subscription-cancel', {
        detail: subscriptionDetailsOptions.clickIdentifier,
      });
      subscriptionDetailsOptions.onSubscriptionCancel = () => {
        document.dispatchEvent(clickEvent);
      };
    }

    return clerk.__internal_openSubscriptionDetails(subscriptionDetailsOptions);
  });
</script>
